﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Windows.Forms.DataVisualization.Charting;

namespace BTServer
{
    public partial class Main : Form
    {
        private medicalstaff staff= null;
        BackgroundWorker checkDateBaseWorker = new BackgroundWorker();

        MySqlConnection conn = ConnectionPool.checkOutConnection();
        heartdb context;
        int selected = 0;
        int rowCount = 0;
        public Main()
        {
            InitializeComponent();
            context = new heartdb(conn);
            intiBGWorker();
            checkDateBaseWorker.RunWorkerAsync();
        }

        private void intiBGWorker()
        {
            checkDateBaseWorker.DoWork += new DoWorkEventHandler(checkDateBaseWorker_DoWork);
        }

        void checkDateBaseWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                updateLatestState();
                System.Threading.Thread.Sleep(1000);
                
            }
        }

        public Main(medicalstaff staff)
        {
            InitializeComponent();
            this.staff = staff;
            odjavaToolStripMenuItem1.Text += " ( "+ staff.FirstName + " )";
            context = new heartdb(conn);
            intiBGWorker();
            popUpUsersAndDevices();
            checkDateBaseWorker.RunWorkerAsync();
        }

        private void odjavaToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void popUpUsersAndDevices()
        {
            var query = from d in context.lateststate select d;

            dataGridView1.Rows.Clear();
            int i = 0;
            foreach (var q in query)
            {
                i++;
                rowCount++;
                dataGridView1.Rows.Add(new string[] {i.ToString(), q.firstname, q.lastname, q.heartrate.ToString(), q.oxigenlevel.ToString(), q.bloodpresure.ToString(), q.updatedate.ToString(), q.room, q.id.ToString()});
            }
            updateGraphValues();
        }

        private void updateLatestState()
        {
            var query = from d in context.lateststate select d;
            try
            {
                dataGridView1.Invoke(new MethodInvoker(delegate()
                {
                    //this.dataGridView1.Rows.Clear();
                    int i = 0;
                    Console.WriteLine("row: " + rowCount);
                    foreach (var q in query)
                    {
                        if (i < rowCount)
                        {
                            this.dataGridView1.Rows[i].Cells[0].Value = (i + 1).ToString();
                            this.dataGridView1.Rows[i].Cells[1].Value = q.firstname;
                            this.dataGridView1.Rows[i].Cells[2].Value = q.lastname;
                            this.dataGridView1.Rows[i].Cells[3].Value = q.heartrate.ToString();
                            this.dataGridView1.Rows[i].Cells[4].Value = q.oxigenlevel.ToString();
                            this.dataGridView1.Rows[i].Cells[5].Value = q.bloodpresure.ToString();
                            this.dataGridView1.Rows[i].Cells[6].Value = q.updatedate.ToString();
                            this.dataGridView1.Rows[i].Cells[7].Value = q.room;
                            this.dataGridView1.Rows[i].Cells[8].Value = q.id.ToString();
                        }
                        else
                        {
                            dataGridView1.Rows.Add(new string[] { i.ToString(), q.firstname, q.lastname, q.heartrate.ToString(), q.oxigenlevel.ToString(), q.bloodpresure.ToString(), q.updatedate.ToString(), q.room, q.id.ToString() });
                        }

                        i++;
                    }
                    updateGraphValues();
                }));
            }
            catch(Exception e)
            {
                
            }
        }

        private void noviPacijentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewPatient np = new NewPatient();
            if (np.ShowDialog() == DialogResult.OK)
            {
                MySqlConnection conn = ConnectionPool.checkOutConnection();
                heartdb db = new heartdb(conn);
                patient p = new patient();
                p.FirstName = np.FirstName;
                p.LastName = np.LastName;
                p.MedicalNumber = np.MedicalId;
                p.BirthDate = np.birthDate;
                p.PersonalId = np.PersonalId;
                db.patient.InsertOnSubmit(p);
                db.SubmitChanges();
                ConnectionPool.checkInConnection(conn);
            }
        }

        private void dodajNoviUredjajToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewDevice nd = new NewDevice();
            if (nd.ShowDialog() == DialogResult.OK)
            {
                MySqlConnection conn = ConnectionPool.checkOutConnection();
                heartdb db = new heartdb(conn);
                device dev = new device();
                dev.DeviceName = nd.DeviceName;
                dev.PairPin = nd.DeviceCode;
                dev.CreationDate = DateTime.Today;
                dev.Status = "slobodan";
                db.device.InsertOnSubmit(dev);
                db.SubmitChanges();
                ConnectionPool.checkInConnection(conn);
            }
        }

        private void izmjeniPodatkeOUredjajuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdateDevice up = new UpdateDevice();
            up.Show();
        }

        private void promjeniUredjajToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdatePatient up = new UpdatePatient();
            up.Show();
        }

        private void izmjeniPodatkeOPacijentuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ViewGraph vg = new ViewGraph();
            vg.Show();
        }

        private void updateGraph(List<decimal> values)
        {
            chart1.Series["Oxigen Level"].Points.Clear();
            for (int pointIndex = 0; pointIndex < values.Count(); pointIndex++)
            {
                chart1.Series["Oxigen Level"].Points.AddY(values[pointIndex]);
            }
        }

        private void updateGraphValues()
        {
            List<decimal> values = new List<decimal>();
            int id;
            if (dataGridView1.SelectedRows.Count > 0)
            {
                if (dataGridView1.SelectedRows[0].Cells["id"].Value != null)
                {
                    id = Int32.Parse(dataGridView1.SelectedRows[0].Cells["id"].Value.ToString());
                    MySqlConnection conn = ConnectionPool.checkOutConnection();
                    heartdb db = new heartdb(conn);
                    var query = from la in db.latestactivity where la.DevicehasPatientid == id select new { oxigenLevel = la.OxigenLevel };
                    foreach (var q in query)
                    {
                        values.Add(q.oxigenLevel);
                    }
                    updateGraph(values);
                }
            }
        }

        private void dataGridView1_Click(object sender, EventArgs e)
        {
            selected = dataGridView1.Rows.IndexOf(dataGridView1.SelectedRows[0]);
            Console.WriteLine(selected);
            updateGraphValues();
        }
        bool isChanged = false;
    }
}
